import axios from 'axios';
import {config} from "@/utils/axios/config.js";
import {useUserStore} from "@/store/module/userStore.js";
import qs from "qs";
import {ElMessage} from "element-plus";
import { useGlobalStore} from "@/store/index.js";

const service = axios.create({
    baseURL: config.baseUrl,
    timeout: config.requestTimeout,
    withCredentials: true
})

// 请求白名单，有些请求无需加token
const whiteList = ['/login']

service.interceptors.request.use(config => {
    const { changeLoading } = useGlobalStore();
    changeLoading(true)
    // 是否需要token
    let noToken = (config.headers || {}).isToken === false;
    noToken = whiteList.some(v => (config.url.indexOf(v) > -1) && (noToken = true));
    const token = useUserStore().getToken;
    if (!noToken && token) {
        config.headers.token = token;
    }

    const params = config.params || {}
    const data = config.data || false

    // post 表单提交
    if (config.method.toUpperCase() === 'POST' && (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') && data) {
        config.data = qs.stringify(data);
    }

    // get参数编码
    if (config.method?.toUpperCase() === 'GET' && params) {
        let url = config.url + '?'
        for (const propName of Object.keys(params)) {
            const value = params[propName]
            if (value !== void 0 && value !== null && typeof value !== 'undefined') {
                if (typeof value === 'object') {
                    for (const val of Object.keys(value)) {
                        const params = propName + '[' + val + ']'
                        const subPart = encodeURIComponent(params) + '='
                        url += subPart + encodeURIComponent(value[val]) + '&'
                    }
                } else {
                    url += `${propName}=${encodeURIComponent(value)}&`
                }
            }
        }
        // 给 get 请求加上时间戳参数，避免从缓存中拿数据
        // const now = new Date().getTime()
        // params = params.substring(0, url.length - 1) + `?_t=${now}`
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }

    return config;
}, error => {
    const { changeLoading } = useGlobalStore();

    changeLoading(false)
    console.error('Request interceptor error:', error);
    return Promise.reject(error)
})

service.interceptors.response.use(response => {
    const { changeLoading } = useGlobalStore();

    const {data} = response;

    // 二进制数据则直接返回
    if (
        response.request.responseType === 'blob' ||
        response.request.responseType === 'arraybuffer'
    ) {
        return response.data
    }

    // 获取错误信息
    const msg = data.msg;
    const code = data.code;
    changeLoading(false)

    if (code !== 200) {
        if(code === 401){
            ElMessage.error("登录过期！");
            return useUserStore().logoutAction();
        }
        else if (code === 500) {
            ElMessage.error("服务器错误！");
            return Promise.reject(new Error("服务器错误！"))
        }

        ElMessage.error(msg);
        return Promise.reject('error')
    }  else {
        return data;
    }
}, (error) => {
    const { changeLoading } = useGlobalStore();

    changeLoading(false)

    const { message } = error;
    ElMessage.error(message)

    return Promise.reject(error);
})

export default service;